package cn.example.vip.mall.goods.service.impl;

import cn.example.vip.mall.goods.entity.*;
import cn.example.vip.mall.goods.mapper.BrandMapper;
import cn.example.vip.mall.goods.mapper.CategoryMapper;
import cn.example.vip.mall.goods.mapper.SkuMapper;
import cn.example.vip.mall.goods.mapper.SpuMapper;
import cn.example.vip.mall.goods.service.SpuService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu> implements SpuService {
	
	@Autowired
	CategoryMapper categoryMapper;
	@Autowired
	BrandMapper brandMapper;
	@Autowired
	SkuMapper skuMapper;
	@Autowired
	private SpuMapper spuMapper;
	
	@Override
	public void saveProduct(Product product) {
		// 1. 保存Spu
		Spu spu = product.getSpu();
		spu.setIsMarketable(1);	// 已上架
		spu.setIsDelete(0);	// 未删除
		spu.setStatus(1);	// 已审核
		spuMapper.insert(spu);
		// 2. 保存Sku
		Date date = new Date();
		Category category = categoryMapper.selectById(spu.getCategoryThreeId());
		Brand brand = brandMapper.selectById(spu.getBrandId());
		for(Sku sku : product.getSkus()){
			// Sku名称
			StringBuilder name = new StringBuilder(spu.getName());
			Map<String,String> skuAttribute = JSON.parseObject(sku.getSkuAttribute(), Map.class);
			for(Map.Entry<String, String> entry : skuAttribute.entrySet()){
				name.append("  ").append(entry.getValue());
			}
			sku.setName(name.toString());
			// 创建时间
			sku.setCreateTime(date);
			// 修改时间
			sku.setUpdateTime(date);
			// 分类id
			sku.setCategoryId(spu.getCategoryThreeId());
			// 分类名称
			sku.setCategoryName(category.getName());
			// 品牌id
			sku.setBrandId(spu.getBrandId());
			// 品牌名称
			sku.setBrandName(category.getName());
			// spu_id
			sku.setSpuId(spu.getId());
			// 审核状态
			sku.setStatus(spu.getStatus());
			skuMapper.insert(sku);
		}
	}
	
	@Override
	public Product findProductBySpuId(String spuId) {
		// 查询Spu
		Spu spu = spuMapper.selectById(spuId);
		// 查询sku
		QueryWrapper<Sku> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("spu_id", spuId);
		List<Sku> skus = skuMapper.selectList(queryWrapper);
		
		Product product = new Product();
		product.setSpu(spu);
		product.setSkus(skus);
		return product;
	}
}
